package org.easyx.ui.controller;

import java.io.File;

import org.easyx.core.entity.Constants;
import org.easyx.core.utils.FileUtil;
import org.easyx.core.utils.ObjKit;
import org.easyx.ui.base.BossEasyUIBaseController;
import org.easyx.ui.util.TwoDimensionCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
public class ToolController extends BossEasyUIBaseController {
	private static final Logger log = LoggerFactory.getLogger(CommonsController.class);
	
	private static final String QRPath = Constants.UPLOAD_PATH+"/twoDimensionalCode/";
	
	/**
	 * 二维码页面
	 */
	@RequestMapping(value="/tools/goTwoDimensionCodePage")
	public String goTwoDimensionCodePage() throws Exception{
		request.setAttribute("QRReadPath", QRPath+"read/");
		return "sys/tools/twoDimensionCode";
	}
	
	/**
	 *	生成二维码
	 */
	@RequestMapping(value="/tools/createTwoDimensionCode")
	@ResponseBody
	public Object createTwoDimensionCode(String encoderContent){
		String encoderImgId = ObjKit.getUUId() +".png"; //encoderImgId此处二维码的图片名
		
		if(ObjKit.isEmpty(encoderContent)){
			return operateError("二维码的内容不能为空！");
		}
		
		try {
			String filePath = getContextPath()+QRPath+"create/";
			if(!new File(filePath).exists()){
				FileUtil.mkDir(filePath);
			}
			
			//执行生成二维码
			TwoDimensionCode.encoderQRCode(encoderContent, filePath+encoderImgId, "png");
			
			return operateSuccess("生成二维码成功！",QRPath+"create/"+encoderImgId);
			
		} catch (Exception e) {
			log.error("生成二维码出现异常",e);
			return operateError("生成二维码出现异常！");
		}
	}
	
	/**
	 *	解析二维码
	 */
	@RequestMapping(value="/tools/readTwoDimensionCode")
	@ResponseBody
	public Object readTwoDimensionCode(String imgId){
		if(ObjKit.isEmpty(imgId)){
			return operateError("请先上传要解析的二维码！");
		}
		try {
			String filePath = getContextPath() + QRPath+"read/" + imgId;  //存放路径
			String readContent = TwoDimensionCode.decoderQRCode(filePath);//执行读取二维码
			
			return operateSuccess("解析成功！", readContent);
		} catch (Exception e) {
			log.error("解析二维码出现异常",e);
			return operateError("解析二维码出现异常！");
		}
	}
	
}
